<?php
namespace Pinenut;
/**
 * Ответ действия
 * 
 * @author kosh
 *
 */
class Response {
	public $content;
	public $data = [];
	public $key = null;
	
	public $exception = null;
	
	protected $options = [
		'noRender' => false,
	];
	
	/**
	 * Хранилище дополнительной информации, 
	 * которая поднимается наверх в иерархии вызовов HMVC
	 * 
	 * @var array
	 */
	protected $channels = [];
	
	/**
	 * Хранилище команд, для накатывания в родителя после восстановаления из кеш
	 * @var array
	 */
	protected $channelsCommands = [];
	
	
	function __toString() {
		return (string)$this->content;
	}
	
	function data() {
		return $this->data;
	}

	function setData($data) {
		return $this->data = $data;
	}	
	function __get($name) {
		if (array_key_exists($name, $this->data)) {
            return $this->data[$name];
        }
	}
	
	function __set($name, $value) {
		return $this->data[$name] = $value;
	}
	
	function noRender($value = null) {
		if (null !== $value) {
			$this->options['noRender'] = $value;
		}
		return $this->options['noRender'];
	}
	
	/**
	 * Добавляем данные в канал, в конец массива
	 * @param string $key
	 * @param $value
	 */
	function append($key, $value) {
		//$this->channels[$key] = isset($this->channels[$key])?(array)$this->channels[$key]:array();
		//array_push($this->channels[$key], $value);
		@$this->channels[$key][] = $value;
		$this->channelsCommands[] = array('append', $key, $value, null);
	}
	
	function prepend($key, $value) {
		$this->channels[$key] = isset($this->channels[$key])?(array)$this->channels[$key]:array();
		array_unshift((array)$this->channels[$key], $value);
		$this->channelsCommands[] = array('prepend', $key, $value, null);
	}
	
	function offset($key, $value, $offset) {
		$this->channels[$key] = isset($this->channels[$key])?(array)$this->channels[$key]:array();
		$this->channels[$key][$offset] = $value;
		$this->channelsCommands[] = array('offset', $key, $value, $offset);
	}
	
	function set($key, $value) {
		$this->channels[$key] = $value;
		$this->channelsCommands[] = array('set', $key, $value, null);
	}
	
	function get($key) {
		return @$this->channels[$key];
	}
	
	function getCommands() {
		return @$this->channelsCommands;
	}
	
	/**
	 * Проигрываем команды из дочернего запроса у себя
	 * @param array $commands
	 */
	function playCommands(array $commands) {
		foreach ($commands as $command) {
			$method = $command[0];
			switch ($method) {
				case 'append':
					$this->append($command[1], $command[2], $command[3]);
					break;
				case 'prepend':
					$this->prepend($command[1], $command[2], $command[3]);
					break;
				case 'offset':
					$this->offset($command[1], $command[2], $command[3]);
					break;
				case 'set':
					$this->set($command[1], $command[2], $command[3]);
					break;
			}
		}
	}
	
	function setException($exception) {
		$this->exception = $exception;
	}
}